package cc.cocosky.imclient;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Application {
	
	private Map<SocketChannel, Session> sessionMap = new HashMap<SocketChannel, Session>();
	private ReadWriteLock lock = new ReentrantReadWriteLock();
	
	
	public Session createSession(SocketChannel channel) {
		Session session = new Session(this, channel);
		lock.writeLock().lock();
		try {
			sessionMap.put(channel, session);
		} finally {
			lock.writeLock().unlock();
		}
		return session;
	}
	
	public void killSession(SocketChannel channel) {
		lock.writeLock().lock();
		try {
			Session session = sessionMap.remove(channel);
			try {
				channel.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			session.destory();
		} finally {
			lock.writeLock().unlock();
		}
	}
	
	public Session getSession(SelectableChannel channel) {
		Session session;
		lock.readLock().lock();
		try {
			session = sessionMap.get(channel);
		} finally {
			lock.readLock().unlock();
		}
		return session;
	}
	
}
